package org.dromara.sms4j.emay.config;

import lombok.extern.slf4j.Slf4j;
import org.dromara.sms4j.api.SmsBlend;
import org.dromara.sms4j.cloopen.config.CloopenConfig;
import org.dromara.sms4j.cloopen.service.CloopenSmsImpl;
import org.dromara.sms4j.comm.exception.SmsBlendException;
import org.dromara.sms4j.comm.factory.BeanFactory;
import org.dromara.sms4j.emay.service.EmaySmsImpl;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


/**
 * 容联云多实例短信配置
 *
 * @author easyorder
 * @date 2023/5/23 20:39
 */
@Slf4j
public class MultipleEmaySmsConfig {

    private static Map<String, SmsBlend> smsBlendMap = new ConcurrentHashMap<>();


    private static MultipleEmaySmsConfig smsConfig;

    /**
     * getAlibabaSms
     * <p> 建造一个短信实现对像
     *
     * @author :Wind
     */
    public static SmsBlend getSmsBlend(String key) {
        if (smsConfig == null) {
            smsConfig = new MultipleEmaySmsConfig();
        }
        SmsBlend smsBlend = smsBlendMap.get(key);
        if (smsBlend == null) {
            throw new SmsBlendException("没有注册实现类");
        }
        return smsBlend;
    }


    public static SmsBlend register(String key, EmayConfig config) {
        if (smsConfig == null) {
            smsConfig = new MultipleEmaySmsConfig();
        }
        SmsBlend smsBlend = smsBlendMap.get(key);
        if (smsBlend == null) {
            smsBlend = new EmaySmsImpl(config, BeanFactory.getExecutor(), BeanFactory.getDelayedTime());
            smsBlendMap.put(key, smsBlend);
        }
        return smsBlend;
    }


    /**
     * refresh
     * <p> 刷新对象
     *
     * @author :Wind
     */
    public static SmsBlend refresh(String key, EmayConfig config) {
        // 如果配置对象为空则创建一个
        if (smsConfig == null) {
            smsConfig = new MultipleEmaySmsConfig();
        }
        //删除原来的
        smsBlendMap.remove(key);
        return register(key, config);
    }

    private MultipleEmaySmsConfig() {
    }
}
